package com.lcy.struct.bTreePlus.disk.virtual;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lcy.struct.bTreePlus.disk.core.BPlusTree;
import com.lcy.struct.bTreePlus.disk.core.BPlusTreeFactory;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lucongyang
 * @date Created in  16:28
 * @description 同于内存里的虚拟树
 */
@Setter
@Getter
public class VirtualBPlus extends BPlusTree {
    /**
     * 子节点
     */
    private List<VirtualBPlus> children;

    public static void buildVirtualTree(VirtualBPlus virtualBPlus, boolean forwardMemory) {
        List<VirtualBPlus> children = new ArrayList<>();
        if (virtualBPlus.getChildrenPosition() != null) {
            for (Long l : virtualBPlus.getChildrenPosition()) {
                BPlusTree c = forwardMemory ? BPlusTreeFactory.getTree(l) : BPlusTree.deserialize(l);
                VirtualBPlus child = copy(c);
                if (child != null && child.getChildrenPosition() != null && child.getChildrenPosition().size() > 0) {
                    buildVirtualTree(child, forwardMemory);
                }
                children.add(child);
            }
        }
        if (children.size() > 0) {
            virtualBPlus.setChildren(children);
        }
    }

    public static VirtualBPlus buildVirtualTree(BPlusTree bPlusTree, boolean forwardMemory) {
        VirtualBPlus virtualBPlus = copy(bPlusTree);
        buildVirtualTree(virtualBPlus, forwardMemory);
        return virtualBPlus;
    }

    public static VirtualBPlus copy(BPlusTree bPlusTree) {
        if (bPlusTree == null) {
            return null;
        }
        VirtualBPlus virtualBPlus = new VirtualBPlus();
        virtualBPlus.setPosition(bPlusTree.getPosition());
        virtualBPlus.setParentPosition(bPlusTree.getParentPosition());
        virtualBPlus.setChildrenPosition(bPlusTree.getChildrenPosition());
        virtualBPlus.setIndexList(bPlusTree.getIndexList());
        virtualBPlus.setDataList(bPlusTree.getDataList());
        virtualBPlus.setLeftPosition(bPlusTree.getLeftPosition());
        virtualBPlus.setRightPosition(bPlusTree.getRightPosition());
        return virtualBPlus;
    }
}
